<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AJAX-POST</title>
</head>

<body>
    <h3 id="data">数据未加载...</h3>
    <button id="btn">发起AJAX请求</button>

    <script>

        btn.onclick = function (e) {
            xhrPost2()
        }

        // "https://www.httpbin.org/post"
        function xhrPost() {
            // 创建一个XHR对象
            const xhr = new XMLHttpRequest();

            // 监听【就绪状态变更事件】
            // xhr.addEventListener("readystatechange", function () {
            //     // 查看就绪状态（xhr.readyState）和服务端响应状态码（xhr.status）
            //     // 如果它们同时就绪且OK
            //     console.log("readystatechange", xhr.readyState, xhr.status);

            //     if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 299)) {
            //         // 就获取返回数据（xhr.responseText）
            //         console.log(xhr.responseText);

            //         data.innerText = xhr.responseText;
            //     }
            // });

            xhr.addEventListener(
                "load",//xhr.readystate是4且xhr.status为2字头
                ()=>data.innerText = xhr.responseText
            );

            xhr.addEventListener("error",(err)=>data.innerText = JSON.stringify(err))

            // 配置请求方式和请求路径 建立连接
            xhr.open("POST", "https://www.httpbin.org/post");

            //发送合适的请求头信息
            // 以Content-type请求头告诉服务端我携带的请求体是什么数据类型
            xhr.setRequestHeader(
                "Content-type",
                "application/x-www-form-urlencoded"
                // "application/json"
            );

            // 发送POST请求并携带数据（请求体）
            xhr.send("username=admin&pwd=123456");//携带表单数据
            // xhr.send(JSON.stringify({username:"admin",password:"123456"}));//携带JSON数据

            console.log("请求已发送");
        }
    
        /* 练习 */
        function xhrPost2(){
            const xhr = new XMLHttpRequest()
            // xhr.onreadystatechange = function(){
            //     console.log(xhr.readyState,xhr.status);
            //     if(xhr.readyState===4 && xhr.status>=200 && xhr.status<=299){
            //         data.innerText = xhr.responseText
            //     }
            // }
            xhr.onload = ()=>data.innerText = xhr.responseText
            xhr.onerror = (err)=>data.innerText = JSON.stringify(err)

            
            xhr.open("POST","http://www.httpbin.org/post")

            xhr.setRequestHeader("Content-Type","application/json")
            xhr.send(JSON.stringify({name:"heige",pwd:"654321"}))

            // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
            // xhr.send("name=heige&pwd=111111")//'key1=value1&key2=value2' searchParams/queryString
            
            console.log("request has been sent!");
        }
    </script>
</body>

</html>